/*
 *                        .::::.
 *                      .::::::::.
 *                     :::::::::::
 *                  ..:::::::::::'
 *               '::::::::::::'
 *                 .::::::::::
 *            '::::::::::::::..
 *                 ..::::::::::::.
 *               ``::::::::::::::::
 *                ::::``:::::::::'        .:::.
 *               ::::'   ':::::'       .::::::::.
 *             .::::'      ::::     .:::::::'::::.
 *            .:::'       :::::  .:::::::::' ':::::.
 *           .::'        :::::.:::::::::'      ':::::.
 *          .::'         ::::::::::::::'         ``::::.
 *      ...:::           ::::::::::::'              ``::.
 *     ````':.          ':::::::::'                  ::::..
 *                        '.:::::'                    ':'````..
 *
 * @Descripttion:
 * @version:
 * @Date: 2021-04-20 11:06:21
 * @LastEditors: huzhushan@126.com
 * @LastEditTime: 2022-09-27 18:17:20
 * @Author: huzhushan@126.com
 * @HomePage: https://huzhushan.gitee.io/vue3-element-admin
 * @Github: https://github.com/huzhushan/vue3-element-admin
 * @Donate: https://huzhushan.gitee.io/vue3-element-admin/donate/
 */

import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useApp } from '@/pinia/modules/app'

const service = axios.create({
  baseURL: '/api',
  timeout: 20000,
  withCredentials: true,
})

// 拦截请求
service.interceptors.request.use(
  config => {
    const { authorization } = useApp()
    if (authorization) {
      // config.headers.token = `${authorization.token}`
      config.headers.token = `${authorization}`
    }
    return config
  },
  error => {
    // console.log(error);
    return Promise.reject(error)
  }
)

// 拦截响应
service.interceptors.response.use(
  // 响应成功进入第1个函数，该函数的参数是响应对象，响应成功但可能业务操作失败
  async response => {
    const { code, message } = response.data
    // 响应成功
    if (code === 20000) {
      return response.data
    }

    // 如果响应码是 40104 ，则请求获取新的 token
    if (code === 40104) {
      const { authorization, clearToken, setToken } = useApp()
      // 没有token
      if (!authorization) {
        if (router.currentRoute.value.name === 'login') {
          return Promise.reject(new Error(message || 'Error'))
        }
        const redirect = encodeURIComponent(window.location.href)
        router.push(`/login?redirect=${redirect}`)
        // 清除token
        clearToken()
        setTimeout(() => {
         /*  ElMessage.closeAll()
          try {
            ElMessage.error(message)
          } catch (err) {
            ElMessage.error(message)
          } */
        })
        return Promise.reject(new Error(message || 'Error'))
      } else {
        // token失效，重新登录
        const redirect = encodeURIComponent(window.location.href)
        router.push(`/login?redirect=${redirect}`)
        // 清除token
        clearToken()
        setTimeout(() => {
          ElMessage.closeAll()
        })
        return Promise.reject(new Error(message || 'Error'))
      }
    }

    // 配置了blob，不处理直接返回文件流
		if (response.config.responseType === 'blob') {
			if (response.status === 200) {
				return response
			} else {
				ElMessage.warning('文件下载失败或此文件不存在')
				return
			}
		}

    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response
    }

    // 显示错误
    ElMessage.error(message || 'Error')

    // 返回错误
    return Promise.reject(new Error(message || 'Error'))
  },
  // 响应失败进入第2个函数，该函数的参数是错误对象
  async error => {
    // console.dir(error) // 可在此进行错误上报
    ElMessage.closeAll()
    try {
      ElMessage.error(error.response.data.msg)
    } catch (err) {
      ElMessage.error(error.message)
    }

    return Promise.reject(error)
  }
)

export default service
